<template>
  <div class="infinite-container greenTop1">
    <select-role2 @liclick="selperson" ref="childRole" />
    <confirm-id :familyPerson="familyPerson" :person="person" v-if="showCheck" @checkOk="checkOk"></confirm-id>
    <div v-else>
      <div class="bgwhite">
        <mu-tabs :value="activeTab" @change="handleTabChange">
          <mu-tab value="unpay" title="待支付"/>
          <mu-tab value="payed" title="" class="re">
            <mu-select-field fullWidth v-model="selectVaue"  @change="changeHandle" style="position:absolute;right:0;top:6px;text-align:center;">
              <mu-menu-item value="1" title="已支付（今日）"/>
              <mu-menu-item value="2" title="已支付（未执行）"/>
              <mu-menu-item value="3" title="已支付（全部）"/>
            </mu-select-field>
          </mu-tab>
        </mu-tabs>

        <div v-if="activeTab === 'unpay'">
          <empty v-show = "isEmpty"></empty>
          <ul>
            <li v-for="(item, index) in feeList" :key="index">
              <div class="grayBack flex flex_vcenter flex_between">
                <div class="flex flex_vcenter">
                  <mu-checkbox :label="item.departmentName" v-model="selFeeList" :nativeValue="item.identificationNumber"/>
                  <span>({{item.doctorName}})</span>
                </div>
                <span>{{item.costdate}}</span>
              </div>
              <div class="bgwhite">
                <mu-list>
                  <mu-list-item :title="value1.projectType" v-for="(value1, index1) in feeList[index].detailsItems" @click="openDetailInfo(value1, feeList[index].identificationNumber)" :key="index1">
                <span slot="left" class="leftIcon">
                  <i class="iconOk" v-if="selFeeList.indexOf(item.identificationNumber) > -1"></i>
                  <i class="iconOkGray" v-else></i>
                </span>
                    <span slot="right" class="feeText">￥{{value1.amount | saveTwo}}</span>
                  </mu-list-item>
                </mu-list>
              </div>
            </li>
          </ul>
          <div class="flex flex_between flex_vcenter bottomH">
            <mu-checkbox label="全选" v-model="all"/>
            <div>
              <span>合计：</span>
              <span class="feeTextBig">￥{{allFee | saveTwo}}</span>
            </div>
            <mu-raised-button label="结算" primary :disabled="allFee === 0" @click="toPay()"/>
          </div>
        </div>
        <div v-else>
          <ul class="codeBlock" v-if="payedFeeList.length > 0">
            <li v-for="(value, index) in payedFeeList" :key="index">
              <img src="../../assets/images/已执行.png" alt="" class="statusTag" v-show="value.executionStatus === 3">
              <img src="../../assets/images/未发药.png" alt="" class="statusTag" v-show="value.executionStatus === 2">
              <img src="../../assets/images/已发药.png" alt="" class="statusTag" v-show="value.executionStatus === 1">
              <img src="../../assets/images/未执行.png" alt="" class="statusTag" v-show="value.executionStatus === 4">
              <div class="flex flex_center part1" @click="openBarDialog(value)">
                <barcode :value="value.applicationNumber" style="width:90%;height:120px;padding:10px 0;"></barcode>
              </div>
              <ul class="part2">
                <li>
                  <label>收费项目</label>
                  <span>{{value.costName}}</span>
                </li>
                <li>
                  <label>结算时间</label>
                  <span>{{value.costdate}}</span>
                </li>
                <li>
                  <label>合计金额</label>
                  <span>￥{{value.amount | saveTwo}}</span>
                </li>
                <li>
                  <label>备注说明</label>
                  <span class="feeText">{{value.remark}}</span>
                </li>
              </ul>
              <div class="flex flex_right part3" v-show="false">
                <mu-raised-button label="药品清单" primary @click="getPayedDetail(value)" v-if="!value.checkId"/>
                <mu-raised-button label="查看报告" primary to="/mainReportRecord" v-else/>
              </div>

            </li>
          </ul>
          <empty v-else></empty>
        </div>
    </div>

  </div>

    <mu-popup position="bottom" :open="detailFeeDialog" @close="detailFeeDialog = false" popupClass="popupStyle">
      <mu-appbar title="支付明细" class="popupTitle">
        <mu-flat-button slot="right" label="关闭" @click="detailFeeDialog = false"/>
      </mu-appbar>
      <mu-content-block>
        <ul class="popupMainInfo">
          <li>
            <span>就诊科室：</span>
            <span>{{detailInfo.departmentName}}</span>
          </li>
          <li>
            <span>就诊医生：</span>
            <span>{{detailInfo.doctorName}}</span>
          </li>
          <li>
            <span>{{detailInfo.costName}}：</span>
            <span class="feeText">￥{{detailInfo.totalCost | saveTwo}}</span>
          </li>
        </ul>
        <div class="mt10"></div>
        <mu-divider/>
      </mu-content-block>
    </mu-popup>

    <mu-popup position="bottom" :open="detailDrugDialog" @close="detailDrugDialog = false" popupClass="popupStyle">
      <mu-appbar title="药品清单" class="popupTitle">
        <mu-flat-button slot="right" label="关闭" @click="detailDrugDialog = false"/>
      </mu-appbar>
      <mu-content-block>
        <ul class="popupMainInfo">
          <li>
            <span>就诊科室：</span>
            <span>{{drugInfo.departmentName}}</span>
          </li>
          <li>
            <span>就诊医生：</span>
            <span>{{drugInfo.doctorName}}</span>
          </li>
          <li>
            <span>{{drugInfo.costName}}：</span>
            <span class="feeText">￥{{drugInfo.totalCost | saveTwo}}</span>
          </li>
        </ul>
        <div class="mt10"></div>
        <mu-divider/>
        <mu-list>
          <mu-list-item :title="value.drugName" v-for="(value, index) in drugInfo.drugItems" :describeText="value.description" :key="index">
            <div slot="right" class="tcenter">
              <span>{{value.drugNumber}}{{value.drugUnit}}</span>
              <div class="feeText">￥{{value.drugPrice | saveTwo}}</div>
            </div>
          </mu-list-item>
        </mu-list>
      </mu-content-block>
    </mu-popup>

    <mu-dialog :open="barDialog" @close="barDialog = false" titleClass="dialogTitle">
      <div slot="title" class="flex flex_vcenter ">
        <img src="../../assets/images/head_images.png">
        <span>{{barDialogInfo.patientName}}</span>
        <span>{{familyPerson.sexcode | sex}}</span>
        <span>{{patientAge}}岁</span>
      </div>
      <div class="flex flex_center bgwhite">
        <barcode :value="barDialogInfo.applicationNumber"></barcode>
      </div>
    </mu-dialog>
  </div>
</template>

<script>
  import empty from '@/components/empty'
  import SelectRole2 from '../../components/SelectRole2'
  import {commonAjax, RESTFUL_API} from '@/api/api'
  import {formatDateGetAge} from '@/common/js/util'
  import barcode from '@xkeshi/vue-barcode'
  import confirmId from '../../components/confirmId'
  export default {
    data () {
      return {
        activeTab: 'unpay',
        feeList: [],
        familyPerson: JSON.parse(sessionStorage.getItem('familyPerson')),
        person: JSON.parse(sessionStorage.person),
        isEmpty: false,
        selFeeList: [],
        all: false,
        allFee: 0,
        detailFeeDialog: false,
        detailInfo: {},
        payedType: '今日',
        barDialog: false,
        payedFeeList: [],
        barDialogInfo: {},
        patientAge: '',
        drugInfo: {},
        detailDrugDialog: false,
        selectVaue: '1',
        showCheck: false,
        numbers: []
      }
    },
    components: {
      SelectRole2, empty, barcode, confirmId
    },
    filters: {
      saveTwo (val) {
        if (val === null || val === undefined) {
          return ''
        }
        if (val === 0) {
          return 0
        } else if (val.length === 0) {
          return 0
        } else {
          return parseFloat(val).toFixed(2)
        }
      },
      sex (val) {
        if (val === 1) {
          return '男'
        } else {
          return '女'
        }
      }
    },
    watch: {
      'all' (val) {
        if (val) {
          let temp = []
          let numbers = []
          this.feeList.forEach(v => {
            temp.push(v.identificationNumber)
            numbers.push(v.identificationNumber)
          })
          this.selFeeList = temp
          this.numbers = numbers
        } else {
          this.selFeeList = []
          this.numbers = []
        }
      },
      'selFeeList' (val) {
        this.allFee = 0
        this.numbers = []
        for (var i = 0; i < val.length; i++) {
          this.feeList.forEach(v => {
            if (v.identificationNumber === val[i]) {
              this.numbers.push(v.identificationNumber)
              this.allFee += parseFloat(v.totalCost)
            }
          })
        }
      },
      'activeTab' (val) {
        if (val === 'unpay') {
          this.queryMZFee()
        } else {
          this.queryPayed(1)
        }
      }
    },
    mounted () {
      this.patientAge = formatDateGetAge(new Date(this.familyPerson.birthdate))
      if (this.familyPerson.outpatientCardNo) {
        this.showCheck = false
        if (this.$route.query.tab === 'history') {
          this.activeTab = 'payed'
          this.queryPayed(1)
        } else {
          this.activeTab = 'unpay'
          this.queryMZFee()
        }
      } else {
        this.showCheck = true
      }
    },
    methods: {
      checkOk (val) {
        if (val.data.id && val.data.code === 1) { // 已经通过就诊卡认证
          this.familyPerson.outpatientCardNo = val.data.id
          sessionStorage.familyPerson = JSON.stringify(this.familyPerson)
        }
        this.showCheck = false
        this.queryMZFee()
      },
      changeHandle (val) {
        this.queryPayed(val)
      },
      handleTabChange (val) {
        this.activeTab = val
      },
      selperson (val) {
        this.familyPerson = val
        if (!this.familyPerson.outpatientCardNo) {
          this.showCheck = true
        } else {
          this.showCheck = false
          this.queryMZFee()
        }
        sessionStorage.familyPerson = JSON.stringify(val)
      },
      queryPayed (status) { // 1:今日 2：未执行 3：全部
        if (!status) {
          return
        } else if (status === 1) {
          this.payedType = '今日'
        } else if (status === 2) {
          this.payedType = '未执行'
        } else {
          this.payedType = '全部'
        }
        this.$store.commit('UPDATE_LOADING')
        let param = {
          diaStatus: status,
          patientMedicalCardType: 1,
          patientIdentityCardType: this.familyPerson.cardtype,
          patientIdentityCardNumber: this.familyPerson.idcard,
          patientCode: this.familyPerson.patientcode
        }
        commonAjax(RESTFUL_API.listPaymented, param, true).then(res => {
          this.$store.commit('UPDATE_LOADING')
          if (res.data.code === 1) {
            this.payedFeeList = res.data.data
          } else {
            this.$store.commit('UPDATE_TOAST', {message: res.data.message})
          }
        }).catch(res => {
          this.$store.commit('UPDATE_LOADING')
          this.$store.commit('UPDATE_TOAST', {message: '服务忙'})
        })
      },
      queryMZFee () {
        this.$store.commit('UPDATE_LOADING')
        let param = {
          patientMedicalCardType: 1,
          patientIdentityCardType: this.familyPerson.cardtype,
          patientIdentityCardNumber: this.familyPerson.idcard,
          patientCode: this.familyPerson.patientcode
        }
        commonAjax(RESTFUL_API.listPayment, param, true).then(res => {
          this.$store.commit('UPDATE_LOADING')
          if (res.data.code === 1) {
            if (res.data.data.length > 0) {
              this.feeList = res.data.data
            } else {
              this.isEmpty = true
            }
          } else {
            this.$store.commit('UPDATE_TOAST', {message: res.data.message})
          }
        }).catch(res => {
          this.$store.commit('UPDATE_LOADING')
          this.$store.commit('UPDATE_TOAST', {message: '服务忙'})
        })
      },
      openDetailInfo (query, id) {
        this.detailInfo = {}
        this.detailFeeDialog = true
        this.$store.commit('UPDATE_LOADING')
        let param = {
          identificationNumber: id,
          costMerging: query.costMerging
        }
        commonAjax(RESTFUL_API.paymentDetails, param, true).then(res => {
          this.$store.commit('UPDATE_LOADING')
          if (res.data.code === 1) {
            this.detailInfo = res.data.data
          } else {
            this.$store.commit('UPDATE_TOAST', {message: res.data.message})
          }
        }).catch(res => {
          this.$store.commit('UPDATE_LOADING')
          this.$store.commit('UPDATE_TOAST', {message: '服务忙'})
        })
      },
      openBarDialog (param) {
        this.barDialog = true
        this.barDialogInfo = param
      },
      toPay () {
        this.$router.push({
          path: '/mainPay/pay',
          query: {
            numbers: this.numbers,
            totalFee: this.allFee
          }
        })
      },
      getPayedDetail (query) {
        this.drugInfo = {}
        this.$store.commit('UPDATE_LOADING')
        let param = {
          applicationNumber: query.applicationNumber
        }
        commonAjax(RESTFUL_API.listDrug, param, true).then(res => {
          this.$store.commit('UPDATE_LOADING')
          console.log(res.data.code)
          if (res.data.code === 1) {
            this.detailDrugDialog = true
            this.drugInfo = res.data.data
            for (let i in this.drugInfo.drugItems) {
              this.drugInfo.drugItems[i].description = this.drugInfo.drugItems[i].drugFrequency + ' ' + this.drugInfo.drugItems[i].drugConsumption + ' ' + this.drugInfo.drugItems[i].drugRoute
            }
          } else {
            this.detailDrugDialog = false
            this.$store.commit('UPDATE_TOAST', {message: res.data.message})
          }
        }).catch(res => {
          this.$store.commit('UPDATE_LOADING')
          this.$store.commit('UPDATE_TOAST', {message: '服务忙'})
        })
      }
    }
  }
</script>

<style lang="less">
  @import "../../common/css/flex.css";
  @import "../../common/css/vars";
  @color-feeText:#F7A945;
  .bottomH{
    position: fixed;
    bottom: 0;
    width:100%;
    background-color: white;
    height:50px;
    padding:0 10px;
  }
  .popupStyle{
    width:100%;
  }
  .popupTitle{
    color:@color-primary
  }
  .topNav{
    padding:10px;
    background-color: #F3F2F0;
  }
  .grayBack{
    background-color: #F3F2F0;
    height:50px;
    padding:0 10px;
    font-size:16px;
  }
  .leftIcon{
    width:20px;
    height:20px;
  }
  .iconOk{
    display: block;
    width:20px;
    height:20px;
    background-image: url("../../assets/images/iconfont-ok-checked.png");
    background-repeat: no-repeat;
    background-size:100%;
  }
  .iconOkGray{
    display: block;
    width:20px;
    height:20px;
    background-image: url("../../assets/images/iconfont-ok-disabled.png");
    background-repeat: no-repeat;
    background-size:100%;
  }
  .feeText{
    color:@color-feeText
  }
  .feeTextBig{
    color:@color-feeText;
    font-size:20px;
  }
  .whiteBlcok{
    height:20px;
  }
  .part3{
    background-color: white;
    padding:10px 20px;
  }
  .part2{
    background-color: white;
    border-bottom: 1px solid @color-border;
    padding:10px 20px 0 20px;
    li{
      display:flex;
      margin-bottom:10px;
    }
    label{
      color:@color-gray;
      width:100px;
    }
  }
  .part1{
    background-color: white;
    border-bottom: 1px solid @color-border;
  }
  .dialogTitle{
    background: @color-primary;
    padding-bottom: 10px;
    color: #fff;
    img{
      width:60px;
      height:60px;
    }
    span{
      margin-left:10px;
    }
  }
  .popupMainInfo{
    font-size:16px;
  }
  .codeBlock{
    background-color: #F2F2F2;
    .statusTag{
      position:absolute;
      top:150px;
      right:20px;
      width:100px;
    }
    li{
      position: relative;
      width:100%;
      margin-bottom:10px;
    }
  }
</style>
